/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.ferryc.modules.sys.util;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.ferryc.commons.shiro.ShiroDbRealm;
import com.ferryc.modules.sys.entity.SysUser;

/**
 * 用户工具类
 * 
 * @author ThinkGem
 * @version 2013-12-05
 */
@SuppressWarnings("unchecked")
public class UserUtils {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(UserUtils.class);

	public static final String CACHE_AUTH_INFO = "CACHE_AUTH_INFO";

	public static SysUser getShiroUser() {
		return (SysUser) SecurityUtils.getSubject().getPrincipal();
	}

	/**
	 * 获取当前访问用户名
	 * 
	 * @return
	 */
	public static String getLoginUserName() {
		return getShiroUser().getLoginName();
	}

	/**
	 * 获取当前用户
	 * 
	 * @return 取不到返回 new User()
	 */
	public static SysUser getUser() {
		return getShiroUser();
	}

	public static Session getSession() {
		try {
			Subject subject = SecurityUtils.getSubject();
			Session session = subject.getSession(false);
			if (session == null) {
				session = subject.getSession();
			}
			if (session != null) {
				return session;
			}
			// subject.logout();
		} catch (InvalidSessionException e) {

		}
		return null;
	}

	// ============== User Cache ==============

	public static Object getCache(String key) {
		return getCache(key, null);
	}

	public static Object getCache(String key, Object defaultValue) {
		// Object obj = getCacheMap().get(key);
		Object obj = getSession().getAttribute(key);
		return obj == null ? defaultValue : obj;
	}

	public static void putCache(String key, Object value) {
		// getCacheMap().put(key, value);
		getSession().setAttribute(key, value);
	}

	public static void removeCache(String key) {
		// getCacheMap().remove(key);
		getSession().removeAttribute(key);
	}

}
